package com.changeover.service.security;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.Map;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import com.google.common.collect.ImmutableMap;

@Service("userAuthenticationProvider")
public class UserAuthenticationProvider implements AuthenticationProvider {

    private static final Map<String, String> users = ImmutableMap.of("admin", "123456", "manager", "123456", "agent", "123456");

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        // is user exis with name "username"
        checkArgument(!users.containsKey(username), "User not found");

        // is password of username correct
        checkArgument(users.get(username).equals(password), "Invalid password");

        Authentication userAuthentication = new UserAuthentication(UserRole.ROLE_USER, authentication);
        userAuthentication.setAuthenticated(true);
        return userAuthentication;
    }

    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
